from greader2kindle.feed import FeedCollection, FeedEntry

class FeedBuilder(object):

    def __init__(self, greaderconn):
        self.greaderconn = greaderconn
        
    def generateFeeds(self, markUnread = False):
        feeds = []
        feed_names = self.greaderconn.getFeeds()
        for feed_url in feed_names.keys():
            feed_name = feed_names[feed_url]
            print "generate feed:", feed_name
            feedEntries = self.generateFeedEntries(feed_url, markUnread)
            if feedEntries != []:
                feed = self.generateFeedDocument(feed_url, feed_name)
                for feedEntry in feedEntries:
                    feed.addEntry(feedEntry) 
                feeds.append(feed)
        return feeds
    
    def generateFeedEntries(self, feed_url, markUnread):
        feed_entry_list = []
        # retrieve unread feed entries
        feed_dom = self.greaderconn.requestUnread(feed_url)
        # generate a feed entry object from each of these
        for feed_entry in feed_dom.getElementsByTagName(u'entry'):
            gid = self.getFirstOrNone(feed_entry, u'id');
            generated_feed_entry = self.generateFeedEntry(feed_entry)
            if generated_feed_entry != None:
                feed_entry_list.append(generated_feed_entry)
            # mark feed entry as read
            if markUnread:
                self.greaderconn.markAsRead(gid);
        return feed_entry_list
    
    def generateFeedEntry(self, dom):
        # title is mandatory
        title = self.getFirstOrNone(dom, u'title')
        subtitle = self.getFirstOrNone(dom, u'subtitle')
        date = self.getFirstOrNone(dom, u'updated')
        content = ""
        feed_content_el = self.getFirstOrNone(dom, u'content')
        feed_link_el = self.getFirstOrNone(dom, u'link')
        feed_summary_el = self.getFirstOrNone(dom, u'summary')
        # do something
        if feed_summary_el != None:
            content += feed_summary_el
        if feed_content_el != None:
            content += feed_content_el
        if feed_link_el != None:
            content += feed_link_el
        return FeedEntry(date, title, subtitle, content)
    
    def getFirstOrNone(self, dom, tag):
        try:
            return dom.getElementsByTagName(tag)[0].firstChild.data.\
                encode("ascii", "ignore")
        except Exception:
            return None
    
    def generateFeedDocument(self, feed_url, feed_name):
        return FeedCollection(feed_name)